<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <jgsearch
        :searchData="searchData"
        @on-change-change="askData"
        @on-change-changes="askDatadate"
      >
        <template v-slot:button>
          <RadioGroup
            v-model="patientDate"
            type="button"
            @on-change="changeradio"
          >
            <Radio
              :label="item.value"
              v-for="item in daydata"
              :key="item.value"
              >{{ item.name }}</Radio
            >
          </RadioGroup>
        </template>
      </jgsearch>
      <Table
        highlight-row
        :columns="tablecolumns"
        @on-cell-click="cellClick"
        :data="data"
        :loading="loading"
        size="small"
        border
        show-summary
        :summary-method="handleSummary"
      >
        <template slot="callback_member_name" slot-scope="{ row }">
          <a>{{ row.callback_member_name }}</a>
        </template>
        <template slot="duration_num" slot-scope="{ row }">
          <span>{{ formatSeconds(row.duration_num) }}</span>
        </template>
      </Table>
    </Card>
    <Drawer
      title="回访数据"
      v-model="returnVisitDetail"
      width="70%"
      @on-close="closedrawer"
    >
      <Row type="flex" align="middle" :gutter="12" class="ivu-mb-8">
        <Col>
          <Select
            v-model="paramss.last_callback_way_id"
            clearable
            placeholder="请选择回访方式"
            @on-change="askDatas"
            v-width="200"
          >
            <Option
              v-for="item in callbackWayList"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
        </Col>
        <Col>
          <Select
            v-model="paramss.last_callback_state_id"
            clearable
            placeholder="请选择回访状态"
            @on-change="askDatas"
            v-width="200"
          >
            <Option
              v-for="item in callbackStateList"
              :value="item.id"
              :key="item.id"
              >{{ item.title }}</Option
            >
          </Select>
        </Col>
        <Col>
          <Select
            v-model="paramss.patient_diseases_id"
            clearable
            placeholder="请选择一级病种"
            @on-change="changeDis"
            v-width="140"
          >
            <Option
              v-for="item in firstDis"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </Col>
        <Col v-if="secondDis.length > 0">
          <Select
            v-model="paramss.patient_diseases_child_id"
            clearable
            multiple
            placeholder="请选择二级病种"
            @on-change="askDatas"
            style="width:auto;"
          >
            <Option
              v-for="item in secondDis"
              :value="item.value"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </Col>
      </Row>
      <Table
        highlight-row
        :columns="columns2"
        :loading="loadings"
        :data="data2"
        size="small"
        @on-sort-change="sortchange"
      >
        <template slot="basic" slot-scope="{ row }">
          <a @click="handleDetailPatient(row)"
            >{{ row.user_name }} {{ row.gender }} {{ row.age }}岁</a
          >
        </template>
      </Table>
      <div class="ivu-mt iuv-text-center">
        <Page
          show-total
          show-elevator
          show-sizer
          :total="total"
          :current.sync="paramss.page"
          :page-size="paramss.pageSize"
          :page-size-opts="pageOpts"
          @on-change="formSize"
          @on-page-size-change="formChangePage"
        ></Page>
      </div>
    </Drawer>
    <patient-detail
      ref="patientDetail"
      :btnShow="btnShow"
      @cancelDrawer="initial"
    ></patient-detail>
    <!-- <edit-patient
        ref="editPatient"
        @patientfun="askData"
        v-if="!loading"
    />
    <return-visit ref="returnVisit" @patientfuns="askData" /> -->
  </div>
</template>

<script>
import jgsearch from "@/components/search";
import patientDetail from "@/components/patientDetail";
import {
  statisticscallbackreportcallbackreport,
  statisticscallbackreportcallbackreportdetail,
} from "@api/hqapi/indexone";
import dayjs from "dayjs";
export default {
  name: "visitReport",
  components: { jgsearch, patientDetail },
  data() {
    return {
      callbackWayList: [],
      callbackStateList: [],
      firstDis: [],
      secondDis: [],
      loadings: false,
      daydata: [
        { value: "toDay", name: "今天" },
        { value: "yesterDay", name: "昨天" },
        { value: "sevenDay", name: "周" },
        { value: "month", name: "月" },
      ],
      btnShow: [
        {
          name: "v1-patient-index-sub2",
          flag: "v1/patient/index/sub",
        },
        {
          name: "v1-patient-index-edit-remark2",
          flag: "v1/patient/index/edit-remark",
        },
        {
          name: "v1-patient-index-update4",
          flag: "v1/patient/index/update",
        },
        {
          name: "v1-patient-callback-callback-common-list2",
          flag: "v1/patient/callback/callback-common-list",
        },
        {
          name: "v1-patient-index-edit-tags4",
          flag: "v1/patient/index/edit-tags",
        },
        {
          name: "v1-patient-index-edit-tags3",
          flag: "v1/patient/index/edit-tags",
        },
      ],
      loading: false,
      patientDate: "toDay",
      model2: "",
      returnVisitDetail: false,
      total: 0,
      pageOpts: [10, 20, 30, 50],
      columns2: [
        { title: "基本信息", slot: "basic", width: 150 },
        // { title: '患者状态', key: 'state', slot: 'state', width: 100 },
        // { title: '归属人', key: 'belonger', width: 90 },
        {
          title: "下次回访时间",
          key: "next_callback_time",
          width: 120,
        },
        { title: "总回访次数", key: "all_callback_count", width: 100 },
        {
          title: "回访次数",
          key: "callback_count",
          sortable: "custom",
          width: 110,
        },
        {
          title: "回访时间",
          key: "last_callback_time",
          sortable: "custom",
          width: 135,
        },
        { title: "回访方式", key: "last_callback_way_name", width: 110 },
        { title: "回访状态", key: "last_callback_state_name", width: 110 },
        // { title: '标签', key: 'label', width: 125 },
        { title: "城市", key: "city_name", width: 118 },
        { title: "一级病种", key: "diseases_name", width: 110 },
        { title: "二级病种", key: "diseases_child_name", width: 110 },
        {
          title: "回访内容",
          key: "remark",
          minWidth: 125,
          ellipsis: true,
          tooltip: true,
        },
        // {
        //     title: "备注",
        //     key: "remark",
        //     minWidth: 125,
        //     ellipsis: true,
        //     tooltip: true,
        // },
      ],
      data2: [],
      tablecolumns: [],
      columns: [
        {
          title: "回访人",
          slot: "callback_member_name",
          align: "center",
          width: 118,
          fixed: "left",
          renderHeader: (h, params) => {
            return h("div", [
              h("div", [
                h("span", {}, "回访人"),
                h("Icon", {
                  attrs: {
                    color: "#2d8cf0",
                    type: "ios-arrow-forward",
                    size: "16",
                  },
                  style: {
                    fontWeight: "bolder",
                    cursor: "pointer",
                  },
                  on: {
                    click: () => {
                      // console.log(params.row,'rrrr');
                      this.tablecolumns = this.newList;
                      // this.askData();
                    },
                  },
                }),
              ]),
            ]);
          },
        },
        {
          title: "次数",
          key: "callback_num",
          align: "center",
          width: 110,
          fixed: "left",
        },
        {
          title: "人数",
          align: "center",
          key: "callback_patient_num",
          width: 110,
          className: "infocolumn",
          fixed: "left",
        },
        { title: "回访方式", align: "center", children: [] },
        { title: "回访状态", align: "center", children: [] },
        {
          title: "回访工作量",
          align: "center",
          children: [
            {
              title: "通话时长",
              align: "center",
              slot: "duration_num",
              key: "duration_num",
              minWidth: 90,
            },
            {
              title: "微信沟通条数",
              align: "center",
              key: "wechat_num",
              minWidth: 120,
            },
          ],
        },
        { title: "数据年份", align: "center", children: [] },
      ],
      newList: [
        {
          title: "回访人",
          slot: "callback_member_name",
          align: "center",
          width: 118,
          fixed: "left",
          renderHeader: (h, params) => {
            return h("div", [
              h("div", [
                h("span", {}, "回访人"),
                h("Icon", {
                  attrs: {
                    color: "#2d8cf0",
                    type: "ios-arrow-forward",
                    size: "16",
                  },
                  style: {
                    fontWeight: "bolder",
                    cursor: "pointer",
                  },
                  on: {
                    click: () => {
                      // console.log(params.row,'rrrr');
                      this.tablecolumns = this.columns;
                      // this.askData();
                    },
                  },
                }),
              ]),
            ]);
          },
        },
        {
          title: "公海回访",
          key: "type_sea",
          align: "center",
          width: 110,
          fixed: "left",
        },
        {
          title: "鱼池回访",
          key: "type_fish",
          align: "center",
          width: 110,
          fixed: "left",
        },
        {
          title: "私域回访",
          align: "center",
          key: "type_private",
          width: 110,
          className: "infocolumn",
          fixed: "left",
        },
        { title: "回访方式", align: "center", children: [] },
        { title: "回访状态", align: "center", children: [] },
        {
          title: "回访工作量",
          align: "center",
          children: [
            {
              title: "通话时长",
              align: "center",
              slot: "duration_num",
              key: "duration_num",
              minWidth: 90,
            },
            {
              title: "微信沟通条数",
              align: "center",
              key: "wechat_num",
              minWidth: 120,
            },
          ],
        },
        { title: "数据年份", align: "center", children: [] },
      ],

      data: [],
      params: { start_time: "", end_time: "", department_type: "" },
      paramss: {
        page: 1,
        pageSize: 20,
        start_time: "",
        end_time: "",
        member_id: "",
        sort_callback_state: 0,
        sort_last_callback_time: 0,
        callback_count: 0,
        last_callback_state_id: "",
        patient_diseases_id: "",
        patient_diseases_child_id: [],
        last_callback_way_id: "",
      },
      searchData: {
        project: [
          { id: 1, key: "slot", keys: "button" },
          {
            id: 2,
            key: "DatePicker",
            type: "daterange",
            options: {
              disabledDate(date) {
                return date && date.valueOf() > Date.now();
              },
            },
            value: [],
            callback: "changes",
          },
          {
            id: 3,
            key: "Select",
            clearable: true,
            placeholder: "部门类型",
            value: 1,
            childList: [],
            callback: "change",
          },
        ],
      },
    };
  },
  mounted() {
    this.initial();
    this.tablecolumns = this.columns;
  },
  methods: {
    formatSeconds(value) {
      let result = parseInt(value);
      let h =
        Math.floor(result / 3600) < 10
          ? "0" + Math.floor(result / 3600)
          : Math.floor(result / 3600);
      let m =
        Math.floor((result / 60) % 60) < 10
          ? "0" + Math.floor((result / 60) % 60)
          : Math.floor((result / 60) % 60);
      let s =
        Math.floor(result % 60) < 10
          ? "0" + Math.floor(result % 60)
          : Math.floor(result % 60);
      result = `${h}:${m}:${s}`;
      return result;
    },
    handleSummary({ columns, data }) {
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: "合计",
          };
          return;
        }
        const values = data.map((item) => {
          return Number(item[key]);
        });
        if (
          !values.every((value) => {
            return isNaN(value);
          })
        ) {
          const v = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (key === "duration_num") {
            sums[key] = {
              key,
              value: this.formatSeconds(v),
            };
          } else {
            sums[key] = {
              key,
              value: v,
            };
          }
        }
      });

      return sums;
    },
    closedrawer() {
      this.paramss.page = 1;
      this.paramss.pageSize = 20;
      this.total = 0;
    },
    cellClick(row) {
      this.paramss.start_time = this.params.start_time;
      this.paramss.end_time = this.params.end_time;
      this.paramss.member_id = row.callback_member_id;
      this.paramss.last_callback_state_id = "";
      this.paramss.patient_diseases_id = "";
      this.paramss.patient_diseases_child_id = [];
      this.paramss.last_callback_way_id = "";
      (this.secondDis = []), (this.returnVisitDetail = true);
      this.askDatas();
    },
    // 打开患者详细
    handleDetailPatient(row) {
      this.$refs.patientDetail.handleOpen(row);
    },
    /* @函数功能: 分页 */
    formSize(e) {
      this.paramss.page = e;
      this.askDatas();
    },
    /* @函数功能: 每页数量 */
    formChangePage(e) {
      this.paramss.pageSize = e;
      this.askDatas();
    },
    initial() {
      this.changeradio(this.patientDate);
    },
    askData() {
      this.loading = true;
      this.searchData.project.forEach((item) => {
        if (item.id === 2) {
          this.params.start_time = item.value[0];
          this.params.end_time = item.value[1];
        } else if (item.id === 3) {
          this.params.department_type = item.value;
        }
      });
      statisticscallbackreportcallbackreport(this.params).then((res) => {
        this.firstDis = res.header_list.disease;
        this.searchData.project.forEach((item) => {
          if (item.id === 3) item.childList = res.departmen_type_list;
        });
        this.callbackWayList = res.header_list.callback_way_list;
        this.callbackStateList = res.header_list.callback_state_list;
        this.columns[3].children = [];
        this.newList[4].children = [];
        for (let item of res.header_list.callback_way_list.reverse()) {
          this.columns[3].children.push({ ...item, minWidth: 80 });
          this.newList[4].children.push({ ...item, minWidth: 80 });
        }
        this.columns[4].children = [];
        this.newList[5].children = [];
        for (let item of res.header_list.callback_state_list.reverse()) {
          this.columns[4].children.push({ ...item, minWidth: 90 });
          this.newList[5].children.push({ ...item, minWidth: 90 });
        }

        this.columns[6].children = [];
        this.newList[7].children = [];
        let newArr = [];
        let oldArr = [];
        for (let item in res["header_list"]["year_list"]) {
          newArr.push(res["header_list"]["year_list"][item]);
          oldArr.push(res["header_list"]["year_list"][item]);
        }
        for (let item of newArr) {
          this.columns[6].children.push({ ...item, minWidth: 90 });
          this.newList[7].children.push({ ...item, minWidth: 90 });
        }
        this.data = res.list;
        this.loading = false;
      });
    },
    askDatas() {
      this.loadings = true;
      let params = { ...this.paramss };
      params.patient_diseases_child_id = this.paramss.patient_diseases_child_id.join(
        ","
      );
      statisticscallbackreportcallbackreportdetail(params).then((res) => {
        this.loadings = false;
        this.total = res.total;
        this.data2 = res.list;
      });
    },
    changeDis(e) {
      this.paramss.patient_diseases_child_id = [];
      this.secondDis = [];
      this.firstDis.forEach((item) => {
        if (item.value == e) {
          this.secondDis = item.children;
        }
      });
      this.askDatas();
    },
    askDatadate() {
      this.patientDate = "";
      this.askData();
    },
    changeradio(e) {
      let week = dayjs().$W;
      let year = dayjs().$y;
      let months = dayjs().$M + 1;
      let day = dayjs().format("YYYY-MM-DD");
      let yesterDay = dayjs()
        .subtract(1, "day")
        .format("YYYY-MM-DD");
      let sevenDay = "";
      let num;
      if (week === 0) num = 7;
      else num = week;
      sevenDay = dayjs()
        .subtract(num - 1, "day")
        .format("YYYY-MM-DD");
      let month = dayjs(`${year}-${months}-1`).format("YYYY-MM-DD");
      if (e === "toDay") {
        this.searchData.project[1].value = [day, day];
      } else if (e === "yesterDay") {
        this.searchData.project[1].value = [yesterDay, yesterDay];
      } else if (e === "sevenDay") {
        this.searchData.project[1].value = [sevenDay, day];
      } else if (e === "month") {
        this.searchData.project[1].value = [month, day];
      }
      this.params.start_time = this.searchData.project[1].value[0];
      this.params.end_time = this.searchData.project[1].value[1];
      this.askData();
    },
    sortchange(e) {
      this.logs(e);
      if (e.key === "last_callback_state_name") {
        this.paramss.sort_last_callback_time = 0;
        this.paramss.callback_count = 0;
        if (e.order === "desc") {
          this.paramss.sort_callback_state = 2;
        } else if (e.order === "asc") {
          this.paramss.sort_callback_state = 1;
        } else {
          this.paramss.sort_callback_state = 0;
        }
      } else if (e.key === "last_callback_time") {
        this.paramss.sort_callback_state = 0;
        this.paramss.callback_count = 0;
        if (e.order === "desc") {
          this.paramss.sort_last_callback_time = 2;
        } else if (e.order === "asc") {
          this.paramss.sort_last_callback_time = 1;
        } else {
          this.paramss.sort_last_callback_time = 0;
        }
      } else if (e.key == "callback_count") {
        this.paramss.sort_last_callback_time = 0;
        this.paramss.sort_callback_state = 0;
        if (e.order === "desc") {
          this.paramss.callback_count = 2;
        } else if (e.order === "asc") {
          this.paramss.callback_count = 1;
        } else {
          this.paramss.callback_count = 0;
        }
      }
      this.paramss.page = 1;
      this.askDatas();
    },
  },
};
</script>

<style scoped>
/* /deep/td.infocolumn {
    color: #55b6ec;
    cursor: pointer;
} */
/* /deep/.ivu-table-summary td.infocolumn {
    color: #515a6e;
    cursor: auto;
} */
</style>
